package com.Gwo.org.controller;

import com.Gwo.basic.utils.PageList;
import com.Gwo.basic.utils.Result;
import com.Gwo.org.domain.Department;
import com.Gwo.org.query.DepartmentQuery;
import com.Gwo.org.service.IDeptService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Api(value = "部门的API",description="部门相关的功能")
@RequestMapping("/dept")
@RestController
public class DeptController {
    @Autowired
    private IDeptService service;

    @GetMapping("/{id}")
    @ApiOperation(value = "通过ID查询" )
    @Around("pointcut()")
    public Department findById(@PathVariable("id") Long id){
        return service.findById(id);
    }

    @GetMapping
    @Around("pointcut()")
    public List<Department> findAll(){
        return service.findAll();
    }

    @PutMapping
    @Around("pointcut()")
    public Result addOrUpdate(@RequestBody Department department){
        if(department.getId()==null){
            service.add(department);
            return Result.me().success();
        }else {
            service.update(department);
            return Result.me().success();
        }
    }

    @DeleteMapping("/{id}")
    @Around("pointcut()")
    public Result delete(@PathVariable("id") Long id){
        try{
            service.delete(id);
            return Result.me().success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.me().fail();
    }

    @PostMapping
    @Around("pointcut()")
    public PageList<Department> queryByPage(@RequestBody DepartmentQuery query){
        PageList<Department> list = service.queryByPage(query);
        return list;
    }

    @PatchMapping
    @Around("pointcut()")
    public Result batchDelete(@RequestBody List<Long> ids){
        try{
            service.batchDelete(ids);
            return Result.me().success();
        }catch (Exception e){
            e.printStackTrace();
        }
        return Result.me().fail();
    }

    @GetMapping("/tree")
    @Around("pointcut()")
    public List<Department> getDeptTree(){
        List<Department> result = service.getDeptTree();
//        result.forEach(System.out::println);
        return result;
    }
}
